<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >库存管理(财务)</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >财务库存管理</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{ path: '/inventoryManagement/writeFinancialList' }"
          >财务入库冲销</el-breadcrumb-item
        >
        <el-breadcrumb-item>
          编辑<span class="ccui-curr-crumb" :style="{ paddingLeft: '10px' }">{{
            this.writeroffName
          }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <basicInformation
              ref="formDateBUI"
              :storageList="finStorageList"
              @updataList="updataList"
            ></basicInformation>
          </el-tab-pane>
          <el-tab-pane label="采购清单" name="second">
            <contractList
              ref="contractList"
              :storage-list="finStorageList"
              @delectList="delectList"
              :priceFillingMethodType="priceFillingMethodType"
              :editPcConId="editPcConId"
            ></contractList>
          </el-tab-pane>
          <el-tab-pane v-if="isTrue" label="附件" name="third">
            <!-- <attachment ref="attachment"></attachment> -->
            <upload-info ref="contractAppendix" isTab v-model="fileList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <!-- <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" /> -->
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-export"
            @click="submitHandle('submit')"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="resetHandle"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInformation from "./edit/basicInformation";
// import attachment from "./edit/attachment";
import UploadInfo from "@/basa/components/public/uploadInfo2";
import contractList from "./edit/contractList";
import {
  getFinWriteoffById,
  saveFinWriteoff,
  submitFinWriteoff
} from "../api/edit-item";
import { ishasAgentId } from "@/basa/utils";
// import {getFinStorageById} from "../../financeWarehousing/api/edit-item";
// import { savePcConcSubProtocol } from "../../api/contractChange";
// import contractChangeMixins from "@/app/subContractManage/subcontractChange/mixins/contractChangeMixins";
export default {
  name: "edit-item",
  mixins: [],
  components: {
    basicInformation,
    UploadInfo,
    contractList
  },
  data() {
    return {
      activeName: "first",
      finStorageList: [],
      submitFlag: false,
      writeroffName: "", // 冲销单名称
      priceFillingMethodType: "",
      taxRate: 0,
      focus: "formDateBUI",
      summaryMoneyArr: [],
      fileList: [], // 附件上传集合
      isTrue: false,
      editPcConId: "",
      BillData: [], //总数组2
      contractListBool: false //校验变更列表是否为空
    };
  },
  watch: {
    $route(to, form) {
      console.log(form);
      if (to.name == "contractChangeEntry-edit-item") {
        this.getFinWriteoffById();
      }
    }
  },
  created() {
    this.getFinWriteoffById();
  },
  activated() {
    this.activeName = "first";
  },
  methods: {
    updataList(val) {
      console.log(val);
      this.finStorageList = val;
    },
    delectList(val) {
      this.storageList = val.filter(item => item.check != true);
    },
    handleClick(tab, event) {
      console.log(tab, event, this.activeName);
      this.activeName = tab.name;
    },
    // 保存 提交
    submitHandle(name) {
      // 基本信息数据
      console.log(this.$refs.formDateBUI.form);
      // 合同清单数据
      console.log(this.$refs.contractList.tableData);
      // this.getValidate(this.$refs.contractList.tableData);
      this.$refs.formDateBUI.$refs.form.validate(valid => {
        console.log(valid, "validvalid");
        if (valid) {
          // if (this.contractListBool) {
          // 调接口
          if (name == "save") {
            this.saveFinWriteoff(name);
          } else {
            this.submitFinWriteoff(name);
          }
          // } else {
          //   // 弹个窗
          //   this.$message({
          //     type: "error",
          //     message: "变更明细未填写，请编辑后保存",
          //     showClose: true,
          //     ccuiCustom: true
          //   });
          // }
        } else {
          this.$showErrorMessage("入库冲销单基本信息不完整，请编辑后保存");
          this.activeName = "first";
        }
      });
    },
    // edit详情
    getFinWriteoffById() {
      let obj = {
        ids: [this.$route.params.id]
      };
      getFinWriteoffById(obj).then(res => {
        this.isTrue = true;
        res.data.data.writeoffCount = res.data.data.writeoffCount ? res.data.data.writeoffCount.toFixed(3) : '0.000';
        res.data.data.storageMoney = (+res.data.data.storageMoney).toFixed(2);
        res.data.data.writeoffMoney = res.data.data.storageMoney ? (-1 * res.data.data.storageMoney).toFixed(
          2
        ) : '0.00';
        this.writeroffName = res.data.data.writeroffName;
        this.$refs.formDateBUI.form = res.data.data;
        res.data.data.finStorageList.forEach(item => {
          if ((+item.isOtherCost) == 1 || (+item.isServices) == 1) {
            item.unitPriceWithTax = "";
            item.writeoffCount = "";
            if (item.relationList && item.relationList.length > 0) {
              let newList = [];
              item.relationList.forEach(val => {
                val.pkPurmatdetl = val.id;
                newList.push(val.storageCode);
              });
              item.relationCode = newList.join(",");
            } else {
              item.relationCode = "";
            }
          }
        });
        this.fileList = res.data.data.files;
        this.finStorageList = res.data.data.finStorageList;
        this.finStorageList.forEach(item => {
          if ((+item.isOtherCost) == 0 && (+item.isServices) == 0) {
            item.unitPriceWithTax = (+item.unitPriceWithTax).toFixed(2);
            item.writeoffCount = (-1 * (+item.storageCount)).toFixed(3);
          }
          item.moneyWithTax = (-1 * (+item.moneyWithTax)).toFixed(2);
          item.moneyWithoutTax = (-1 * (+item.moneyWithoutTax)).toFixed(2);
        });
        this.fileList.forEach(item => {
          item.createTimeStr = item.createTime;
          item.uploadId = item.fileInfoId;
        });
        this.$refs.contractList.tableData = res.data.data.finStorageList;
      });
    },
    // 保存/提交
    saveFinWriteoff(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId || row.fileInfoId;
        row.createTime = row.createTime ? row.createTime : row.uploadTime;
        row.uploadTime = row.uploadTime ? row.uploadTime : row.createTime;
      });
      this.finStorageList.forEach((item, index) => {
        item.sn = ++index;
      });
      let obj = this.$refs.formDateBUI.form;
      obj.files = fileList1;
      obj.isShowLoading = true;
      obj.loadingMessage = "保存中,请稍等...";
      saveFinWriteoff(obj)
        .then(res => {
          let { code } = res.data;
          this.$message({
            message: "保存并校验成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    submitFinWriteoff(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach(row => {
        row.fileInfoId = row.uploadId || row.fileInfoId;
        row.createTime = row.createTime ? row.createTime : row.uploadTime;
        row.uploadTime = row.uploadTime ? row.uploadTime : row.createTime;
      });
      this.finStorageList.forEach((item, index) => {
        item.sn = ++index;
      });
      let obj = this.$refs.formDateBUI.form;
      obj.files = fileList1;
      obj.storageList = this.finStorageList;
      obj.isShowLoading = true;
      obj.loadingMessage = "提交中,请稍等...";
      submitFinWriteoff(obj)
        .then(res => {
          let { code } = res.data;
          this.$message({
            message: "保存并提交成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch(e => {
          console.log(e);
        });
    },
    // 校验变更列表不能为空
    getValidate(data) {
      if (data.length > 0) {
        data.forEach(item => {
          // if (item.children) {
          if (
            String(item.replyAmount) != null &&
            String(item.replyNumber) != null &&
            String(item.replyPrice) != null &&
            String(item.reportAmount) != null &&
            String(item.reportNumber) != null &&
            String(item.reportPrice) != null
          ) {
            this.contractListBool = true;
          } else {
            this.contractListBool = false;
          }
        });
      }
    },
    // 取消
    resetHandle() {
      this.handleBack();
    },
    handleBack() {
      this.$router.push(
        sessionStorage.getItem("fromPath") ||
          "/contracts/contractChangeEntry/un-submitted"
      );
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(from);
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style lang="scss" scoped>
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}
/deep/ .el-tabs__customize {
    padding-bottom: 50px;
}
</style>
